/**
 *  背景页面脚本对外接口
 */
define(function(require, exports, module) {

  "require:nomunge,exports:nomunge,module:nomunge";

  var common = require('/module/common/common.js');

  //任务
  if ( !window._cache['tasksId'] ) {
    window._cache['tasksId'] = [];
  }
  if ( !window._cache['tasksDetail'] ) {
    window._cache['tasksDetail'] = {};
  }
  if ( !window._cache['tasksRunning'] ) {
    window._cache['tasksRunning'] = [];
  }
  if ( !window._cache['tasksRunningTime'] ) {
    window._cache['tasksRunningTime'] = {};
  }
  if ( !window._cache['tasksComplete'] ) {
    window._cache['tasksComplete'] = [];
  }
  if ( !window._cache['tasksFailed'] ) {
    window._cache['tasksFailed'] = [];
  }
  if ( !window._cache['tasksFailedDetail'] ) {
    window._cache['tasksFailedDetail'] = {};
  }
  if ( !window._cache['tasksComplete'] ) {
    window._cache['tasksComplete'] = [];
  }
  if ( !window._cache['tasksCompleteCount'] ) {
    window._cache['tasksCompleteCount'] = 0;
  }
  if ( !window._cache['tasksForbidId']) {
    window._cache['tasksForbidId'] = [];
  }



  // 将要跳转到的页面
  if ( !window._cache['switchPage'] ) {
    window._cache['switchPage'] = '';
  }
  //初始化用户信息
  if ( !window._cache['userInfo'] ) {
    window._cache['userInfo'] = null;
  }
  if ( !window._cache['companyInfo'] ) {
    window._cache['companyInfo'] = null;
  }

  // 大屏幕列表
  if(!window._cache['companyInfoList']) {
    window._cache['companyInfoList'] = [];
  }

  // 是否需要再次温馨提示
  if ( 'undefined' == typeof window._cache['need_message_warmtip'] ) {
    window._cache['need_message_warmtip'] = true;
  }

  // 是否允许同一用户的重复言论上墙
  if('undefined' == typeof window._cache['is_allow_user_repeat_message']) {
    window._cache['is_allow_user_repeat_message'] = null;
  }

  // 自动上墙开始时间
  if('undefined' == typeof window._cache['auto_wall_start_time']) {
    window._cache['auto_wall_start_time'] = null;
  }

  // 自动上墙的开关
  if ('undefined' == typeof window._cache['auto_wall_is_open']) {
    window._cache['auto_wall_is_open'] = 0;
  }

  // 自动上墙的配置
  if (!window._cache['auto_wall_config']) {
    window._cache['auto_wall_config'] = {
      wallTime: 5,
      htmlTime: 8,
      htmlCount: 20
    };
  }

  if(!window._cache['firstCheckLoginInfo']) {
    window._cache['firstCheckLoginInfo'] = null;
  }

  // 本地中奖用户
  if(!window._cache['lotteryLocalData']) {
    window._cache['lotteryLocalData'] = null;
  }

  // 匹配部分上墙
  if(!window._cache['auto_wall_matched_words_arr']) {
    window._cache['auto_wall_matched_words_arr'] = [];
  }

  // 完全匹配关键词
  if(!window._cache['complete_forbid_words_arr']) {
    window._cache['complete_forbid_words_arr'] = [];
  }

  // 部分匹配关键字词库
  if(!window._cache['forbid_words_arr']) {
    window._cache['forbid_words_arr'] = [];
  }

  // 默认关键词库
  if(!window._cache['forbid_words_default_arr']) {
    window._cache['forbid_words_default_arr'] = [];
  }

  // 是否配置完毕
  if(!window._cache['is_setting_complete']) {
    window._cache['is_setting_complete'] = null;
  }

  // 已经发送消息
  if(!window._cache['sent_message_box']) {
    window._cache['sent_message_box'] = {};
  }

  // 错误类型
  if(!window._cache['sent_error_type']) {
    window._cache['sent_error_type'] = ['forbid_words', 'forbid_words_default', 'repeat_message', 'over_start_time'];
  }

  /**
   * 获取关键词配置
   */
  exports.getRuleWords = function(type)
  {
    type = type || 'match';
    if(type == 'match') {
      return window._cache['forbid_words_arr'];
    } else if (type == 'complete') {
      return window._cache['complete_forbid_words_arr'];
    } else if(type == 'auto_wall') {
      return window._cache['auto_wall_matched_words_arr'];
    }
  };

  /**
   * 设置关键词过滤
   */
  exports.setRuleWords = function(content, type)
  {
    content = content.trim().replace(/\s+/g, '@').replace(/^@/, '').replace(/@$/, '');

    var companyInfo = this.getCompanyInfo();

    // 完全匹配和部分匹配
    type = type || 'match';

    if(type == 'match') {
      window._cache['forbid_words_arr'] = content.split('@');
      companyInfo.forbid_words = content;
    } else if(type == 'complete') {
      window._cache['complete_forbid_words_arr'] = content.split('@');
      companyInfo.complete_forbid_words = content;
    } else if(type == 'auto_wall') {
      window._cache['auto_wall_matched_words_arr'] = content.split('@');
      companyInfo.auto_wall_matched_words = content;
    }

    this.setCompanyInfo(companyInfo);

    return true;
  };


  exports.setFirstCheckLoginInfo = function(info)
  {
    window._cache['firstCheckLoginInfo'] = info;
  };

  exports.getFirstCheckLoginInfo = function(info)
  {
    return window._cache['firstCheckLoginInfo'];
  };


  /**
   * 添加任务
   */
  exports.taskAdd = function(msg, sender, cb)
  {
    if (!msg.task) return cb({'result':false, 'error_msg':'task is empty'});

    for(var i=0; i < msg.task.length; i++) {
      var id = parseInt(msg.task[i].id);
      if (
        window._cache['tasksId'].indexOf(id) == -1
        && window._cache['tasksComplete'].indexOf(id) == -1
        && window._cache['tasksFailed'].indexOf(id) == -1
        && window._cache['tasksRunning'].indexOf(id) == -1
      ) {
        // 初始化执行次数为0
        if(!msg.task[i].runTimes) msg.task[i].runTimes = 0;
        window._cache['tasksId'].push(id);
        // 此处不覆盖正在执行的任务
        if (!window._cache['tasksDetail'][id] || !window._cache['tasksDetail'][id].runTimes) {
          window._cache['tasksDetail'][id] = msg.task[i];
        }
      }
    }
    cb({'result':true, 'detail':this.taskStatus()});
  };

  /**
   * 获取一个任务
   */
  exports.taskGetOne = function(msg, sender, cb)
  {
    var id = window._cache['tasksId'].shift();
    if (!id) return cb({"result": true, "task":null});
    var task = window._cache['tasksDetail'][id];
    if (!task) return cb({"result":false, "error_msg":"上墙任务详情未能获取到", "id":id});

    window._cache['tasksRunning'].push(id);
    window._cache['tasksRunningTime'][id] = (new Date).getTime();

    cb({'result':true, 'task':task, 'detail': this.taskStatus()});
  };

  /**
   * 完成一个任执行
   * @return
   */
  exports.taskCompleteOne = function(msg, sender, cb)
  {
    if (!msg.task) return cb({'result':false, 'error_msg':'task is empty'});

    var id           = parseInt(msg.task.id);
    var returnStatus = null;

    // 删除正在运行的
    var idx = window._cache['tasksRunning'].indexOf(id);
    if (idx > 0) {
      window._cache['tasksRunning'].splice(idx, 1);
      delete window._cache['tasksRunningTime'][id];
    }

    var taskDetail = window._cache['tasksDetail'][id];
    if (!taskDetail) return cb({'result':false, 'error_msg':'taskDetail is empty'});

    // 失败，重新添加
    // 每个任务最多执行3
    if (!msg.result && taskDetail.runTimes < 1 && window._cache['sent_error_type'].indexOf(msg.error_type) == -1) {

      taskDetail.runTimes++;
      this.taskAdd({'task':[taskDetail]}, null, function(){});

      returnStatus = 'again';

    } else if (!msg.result) {

      taskDetail.error_msg = msg.error_msg;
      window._cache['tasksFailed'].unshift(id);
      window._cache['tasksFailedDetail'][id] = taskDetail;
      // 只保留最近错误的1000条
      if(window._cache['tasksFailed'].length >5000) {
        window._cache['tasksFailed'] = window._cache['tasksFailed'].slice(0, 5000);
        var keys = Object.keys(window._cache['tasksFailedDetail']);
        var key;
        for(var i = 0; i < keys.length; i++) {
          key = parseInt(keys[i]);
          if(!key) continue;
          if(window._cache['tasksDetail'].indexOf(key) == -1) {
            delete window._cache['tasksFailedDetail'][key];
          }
        }
      }

      returnStatus = 'failed';

      // 禁止上墙的
      if ( window._cache['tasksForbidId'].indexOf(id) == -1 && window._cache['sent_error_type'].indexOf(msg.error_type) != -1) {
        window._cache['tasksForbidId'].push(id);
      }

    } else{

      delete window._cache['tasksDetail'][id];
      window._cache['tasksComplete'].unshift(id);
      if (window._cache['tasksComplete'].length > 100000) {
        window._cache['tasksComplete'] = window._cache['tasksComplete'].slice(0, 100000);
      }
      window._cache['tasksCompleteCount']++;

      returnStatus = 'success';
    }

    cb({'result':true, 'detail': this.taskStatus(), 'returnStatus':returnStatus});
  };

  /**
   * 获取任务详情
   */
  exports.taskStatus = function(msg, sender, cb)
  {
    var data = {
      'completeCount': window._cache['tasksCompleteCount'],
      'leftCount': window._cache['tasksId'].length,
      'failedCount': window._cache['tasksFailed'].length,
      'forbidId': window._cache['tasksForbidId']
    };

    if(cb) cb({'result':true, 'detail':data});
    return data;
  };

  /**
   * 校验正在运行的task，如果失败或者未执行成功，则放到失败、成功的队列
   */
  exports.taskCheckRunning = function()
  {
    if (window._cache['tasksRunning'].length == 0) return true;

    var nowT = (new Date).getTime();
    // 2小时
    var maxT = 2*3600*1000;
    var me   = this;

    for(var i = 0; i < window._cache['tasksRunning'].length; i++) {

      var id = window._cache['tasksRunning'][i];

      // 在未执行的任务中 || 在已完成的队列中 || 在已失败的队列中
      if(
        window._cache['tasksId'].indexOf(id) != -1
        || window._cache['tasksComplete'].indexOf(id) != -1
        || window._cache['tasksFailed'].indexOf(id) != -1
        ) {
        window._cache['tasksRunning'].splice(i, 1);
        i --;
        continue;
      }

      // 没有在任何队列中（查看执行时间）
      var startT = window._cache['tasksRunningTime'][id];
      // 3无产品，丢弃
      if(!startT) {
        window._cache['tasksRunning'].splice(i, 1);
        i --;
        continue;
      }
      if( nowT-startT > maxT) {
        window._cache['tasksRunning'].splice(i, 1);
        i --;
        // 如果有详情则重新加入到队列
        if(window._cache['tasksDetail'][id]) {
          window._cache['tasksDetail'][id].runTimes = 0;
          me.taskAdd({"task": window._cache['tasksDetail'][id]}, null, function(){ });
        }
        continue;
      }
    }
  };

  /**
   * 任务恢复
   * @return {[type]} [description]
   */
  exports.taskUnserialize = function()
  {
    var companyInfo = this.getCompanyInfo();
    if (!companyInfo) return false;

    var key = "wxscreen#task#"+companyInfo.id;
    var S = localStorage.getItem(key);
    if(!S) return true;

    try {
      S = JSON.parse(S);
    } catch(e) {
      console.log('taskUnserialize error', e);
      return false;
    }

    // 恢复数据
    var t = (new Date).getTime() - S.addTime;
    // 大于6小时，不恢复
    if(t > 6*3600*1000) {
      localStorage.removeItem(key);
      return true;
    }

    // 目前只恢复已经完成的数据
    window._cache['tasksComplete']      = S['tasksComplete'] ? S['tasksComplete'] : [];
    window._cache['tasksCompleteCount'] = S['tasksCompleteCount'] ? S['tasksCompleteCount'] : 0;
    // 被禁止的
    window._cache['tasksForbidId'] = S['tasksForbidId'] ? S['tasksForbidId'] : [];
  };

  /**
   * 任务序列化，方便恢复
   */
  exports.taskSerialize = function()
  {
    var companyInfo = this.getCompanyInfo();
    if (!companyInfo) return false;

    if(companyInfo.is_auto_wall != 1) return false;

    // 序列化已经完成的
    var S = {};
    var keys = Object.keys(window._cache);
    for(var i =0; i<keys.length; i++) {
      if (keys[i].indexOf('task') == 0) {
        S[keys[i]] = window._cache[keys[i]];
      }
    }

    // 时间版本
    S.addTime = (new Date).getTime();

    var key = "wxscreen#task#"+companyInfo.id;
    try {
      localStorage.setItem(key, JSON.stringify(S));
    } catch(e) {
      console.log('taskSerialize error', e);
    }
  };

  /**
   * 设置用户信息
   */
  exports.setUserInfo = function(userInfo){
    window._cache['userInfo'] = userInfo;
  };

  /**
   * 获取用户信息
   */
  exports.getUserInfo = function(){
    return window._cache['userInfo'];
  };

  /**
   * 设置公司info
   */
  exports.setCompanyInfo = function(companyInfo){
    window._cache['companyInfo'] = companyInfo;
    localStorage.setItem("currentCompanyId", companyInfo.id);
  };

  /**
   * 设置公司列表
   */
  exports.setCompanyInfoList = function(list)
  {
    window._cache['companyInfoList'] = list;
    /*$.each(list, function(k, v){
      window._cache['companyInfoList'][v.id] = v;
    });*/
    return true;
  };

  /**
   * 获取公司列表
   */
  exports.getCompanyInfoList = function()
  {
    return window._cache['companyInfoList'];
  };

  /**
   * 获取公司info
   */
  exports.getCompanyInfo = function()
  {
    if (window._cache['companyInfo']) {
      var id = window._cache['companyInfo'].id || localStorage.getItem("currentCompanyId");
      var flag = false, tmpInfo;
      $.each(window._cache['companyInfoList'], function(){
        if(this.id == id) {
          flag = true;
          tmpInfo = this;
          return false;
        }
      });
      if(flag) {
        window._cache['companyInfo'] = tmpInfo;
        localStorage.setItem("currentCompanyId", tmpInfo.id);
        return window._cache['companyInfo'];
      }
    }

    window._cache['companyInfo'] = null;

    if(!window._cache['companyInfoList'][0]) {
      return null;
    }
    window._cache['companyInfo'] = window._cache['companyInfoList'][0];

    return window._cache['companyInfo'];
  };

  /**
   * 获取自动上墙的开关
   */
  exports.getAutoWallStatus = function(msg, sender, cb)
  {
    if (cb) cb({'result':true, 'data':window._cache['auto_wall_is_open'], 'config': this.getAutoWallConfig()});
    return window._cache['auto_wall_is_open'];
  };

  /**
   * 获取自动上墙配置
   */
  exports.getAutoWallConfig = function()
  {
    return window._cache['auto_wall_config'];
  };

  /**
   * 设置自动上墙的配置
   */
  exports.setAutoWallConfig = function(config)
  {
    window._cache['auto_wall_config'] = config;
  };

  /**
   * 设置自动上墙的开关
   */
  exports.setAutoWallStatus = function(flag)
  {
    window._cache['auto_wall_is_open'] = flag;
  };

  /**
   * 是否处于SettingPage
   * @link https://mp.weixin.qq.com/cgi-bin/userinfopage?t=wxm-setting&token=866702323&lang=zh_CN
   * @link2 https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&token=1285298060&lang=zh_CN
   */
  exports.getSettingPageTab = function(cb){
    chrome.tabs.query({
      url: "https://mp.weixin.qq.com/cgi-bin/settingpage*",
      windowType: "normal"
    }, function(tabs){
      if ( tabs.length ) {
        cb(tabs[0]);
      } else {
        cb(null);
      }
    });
  };

  /**
   * 将某个tab页设置为当前tab
   */
  exports.setCurrTab = function(tab, config, cb) {
    chrome.tabs.update(tab.id, config, cb);
  };

  /**
   * 创建一个tab
   */
  exports.createTab = function(config, cb) {
    chrome.tabs.create(config, cb);
  };

  /**
   * 获取配置页面的url地址
   * @see  https://mp.weixin.qq.com/cgi-bin/userinfopage?t=wxm-setting&token=2099643725&lang=zh_CN
   * @see  https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&token=1285298060&lang=zh_CN
   */
  exports.getSettingPageUrl = function(cb, urlArr){
    if ( urlArr && urlArr.queryParams.token ) {
      cb('https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&token='+urlArr.queryParams.token+'&lang=zh_CN');
      return;
    }
    chrome.tabs.query({
      url: "https://mp.weixin.qq.com/cgi-bin/*",
      windowType: "normal"
    }, function(tabs){
      if ( tabs.length ) {
        for( var i =0; i<tabs.length; i++) {
          var urlArr = common.parseUrl(tabs[i].url);
          if ( urlArr.queryParams.token ) {
            cb('https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&token='+urlArr.queryParams.token+'&lang=zh_CN', tabs[i]);
            return;
          }
        }
      }
      cb('https://mp.weixin.qq.com');
    });
  };

  /**
   * 获取消息页面的url地址
   * @see https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token=2099643725&lang=zh_CN
   */
  exports.getMessagePageUrl = function(cb, urlArr)
  {
    chrome.tabs.query({
      url: "https://mp.weixin.qq.com/cgi-bin/*",
      windowType: "normal"
    }, function(tabs){
      var tab, token;
      if(!tabs.length) {
        cb('https://mp.weixin.qq.com');
        return;
      }
      for( var i =0; i<tabs.length; i++) {
        var urlArr = common.parseUrl(tabs[i].url);
        if (!tab && tabs[i].url.indexOf('cgi-bin/message') != -1) {
          tab   = tabs[i];
        } else {
          // close
          //chrome.tabs.remove(tabs[i].id);
        }
        if(!token && urlArr.queryParams.token) {
          token = urlArr.queryParams.token;
        }
      }
      if(token) {
        cb('https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token='+token+'&lang=zh_CN', tab);
      } else {
        cb('https://mp.weixin.qq.com');
      }
    });
  };

  /**
   * 关闭所有的公众平台的页面
   */
  exports.uniqueMpTabs = function(isCloseAll)
  {
    chrome.tabs.query({
      url: "https://mp.weixin.qq.com/*",
      windowType: "normal"
    }, function(tabs){
      if ( tabs.length ) {
        var idx = isCloseAll ? 0 : 1;
        for( var i =idx; i<tabs.length; i++) {
          chrome.tabs.remove(tabs[i].id);
        }
      }
    });
  };

  /**
   * 设置即将要跳转到的某个页面
   * @param {String} page 'setting'/'message'
   */
  exports.setSwitchPage = function(page){
    window._cache['switchPage'] = page;
  };

  /**
   * 获取即将要跳转的某个页面
   */
  exports.getSwitchPage = function(){
    return window._cache['switchPage'];
  };

  /**
   * 单条消息处理器
   */
  exports.messageHandler = function(msg, sender, resposeFn) {
    var func = msg.func;
    if ( !this[func] ) {
      resposeFn({'error':'func '+func+' is not defined.'});
      return;
    }
    this[func](msg, sender, resposeFn);
  };

  /**
   * 跳转到某页
   */
  exports.switchPage = function(msg, sender, responseFn) {
    var tab = sender.tab;
    var urlArr = common.parseUrl(tab.url);

    // 未登录，不跳转
    if ( !urlArr.queryParams['token'] ) {
      //mpNotification.noti('mp_setting', '登录', '请先登录微信公众平台');
      responseFn({'url':false, 'error':'not_login', 'error_msg':'请先登录微信公众平台'});
      return;
    }

    // 登录提示
    var companyInfo = this.getCompanyInfo();
    if ( !companyInfo || !companyInfo.id ) {
      //mpNotification.noti('user_login', '您还没有登录', '请点击浏览器右上角微信大屏幕图标登录');
      responseFn({'url':false, 'error':'not_login', 'error_msg': '请点击浏览器右上角微信大屏幕图标登录'});
      return;
    }

    mpNotification.close('mp_setting');

    // 获取要跳转的页面并置为空
    var switchPage = this.getSwitchPage();
    this.setSwitchPage('');

    switch ( switchPage ) {
      // setting页面
      case 'setting':
        if ( tab.url.indexOf('wxm-setting') == -1 ) {
          this.getSettingPageUrl(function(url){
            responseFn({'url':url});
          }, urlArr);
        } else {
          responseFn({'url':tab.url});
        }
        break;
      // 实时消息页面
      case 'message':
        if ( tab.url.indexOf('wxm-message') == -1 ) {
          this.getMessagePageUrl(function(url){
            responseFn({'url':url});
          }, urlArr);
        }
        break;
      // 默认不跳转
      default :
        responseFn({'url':false});
    }
  };

  /**
   * isNeedSetting 是否需要配置
   */
  exports.isNeedSetting = function(msg, sender, cb){
    var companyInfo = this.getCompanyInfo();
    if ( !companyInfo || !companyInfo.id ) {
      if (cb) cb({'needSetting': false});
      return false;
    }
    if ( !companyInfo.weixin_name || !companyInfo.weixin_qr_big || !companyInfo.weixin_qr_middle || !companyInfo.weixin_qr ) {
      if (cb) cb({'needSetting': true});
      return true;
    }
    if (cb) cb({'needSetting': false});
    return false;
  };

  /**
   * 获取主持人说的信息
   */
  exports.getPresenterInfo = function(msg, sender, cb)
  {
    var companyInfo = this.getCompanyInfo();
    if(!companyInfo || !companyInfo.id) {
      if(cb) cb({'info': 'companyInfo empty'});
      return false;
    }
    var res = { info: 'ok', name: companyInfo.presenter_name, avatar:companyInfo.presenter_avatar };
    if(cb) cb(res);
    return false;
  };

  /**
   *
   */
  exports.presenter = function(msg, sender, cb)
  {
    var url = this.getUrl('user/extension/presenter', true);
    if(!url) {
      if(cb) cb({info:'get post url failed'});
      return false;
    }
    $.post(url, msg, function(json){
      if(cb) cb(json);
    }, 'json').error(function(jqXHR, errTxt, errThrown){
      if(cb) cb({info: 'ajax-error'});
    });
    return false;
  };

  /**
   *
   */
  exports.syncLocalLotteryData = function(msg, sender, cb)
  {
    var companyInfo = this.getCompanyInfo();
    if ( !companyInfo || !companyInfo.id ) {
      if (cb) cb({'msg': 'companyInfo is empty'});
      return;
    }
    if(msg.data.companyId != companyInfo.id) {
      if (cb) cb({'msg': 'companyId not matched'});
      return;
    }

    window._cache['lotteryLocalData'] = msg.data.data;
    cb({'msg': 'ok'});
  };

  /**
   * 获取本地的中奖数据
   */
  exports.getLocalLotteryData = function()
  {
    var data = window._cache['lotteryLocalData'];
    if(data) {
      for(var i = 0; i < data.length; i++) {
        if(!data[i]) {
          return null;
        }
        data[i].user_name  = data[i].name || data[i].user_name;
        data[i].view_order = i+1;
      }
      return data;
    }
    return null;
  }

  /**
   * content scripts 显示通知
   */
  exports.showNoti = function(msg, sender, cb){
    if ( (msg.is_warmtip && window._cache['need_message_warmtip']) || !msg.is_warmtip ) {
      mpNotification.noti(msg.id, msg.title, msg.content, msg.cover);
      window._cache['need_message_warmtip'] = false;
      cb({'result':true});
    }
  };

  /**
   * 关闭桌面通知
   */
  exports.closeNoti = function(msg, sender, cb){
    mpNotification.close(msg.id);
  };

  /**
   * 显示上墙的消息数目
   */
  exports.setNoticeNum = function(num){
    chrome.browserAction.setBadgeText({
      'text':num
    });
    chrome.browserAction.setBadgeBackgroundColor({
      'color': '#51a351'
    });
  };

  /**
   * 获取上墙的消息总数
   */
  exports.getWallMessageTotal = function(cb){
    var url = this.getUrl('user/extension/get_wall_message_total' , true);
    if ( !url ) {
      cb('url not generated.', null);
      return;
    }
    $.getJSON(url, function(data){
      cb(null, data);
    });
  };

  /**
   * 通知tab下墙消息
   * @param  {[type]} mpId [description]
   * @return {[type]}      [description]
   */
  exports.noticeOffWall = function(mpId)
  {
    chrome.tabs.query({}, function(tabs){
      if ( tabs.length ) {
        for (var i =0; i<tabs.length; i++) {
          if (tabs[i].url && tabs[i].url.indexOf('mp.weixin.qq.com') > -1) {
            chrome.tabs.sendMessage(tabs[i].id, {'func':'offWall', 'mp_message_id':mpId});
          }
        }
      }
    });
  };

  /**
   * 根据mp_id下墙
   */
  exports.offWall = function(msg, sender, cb)
  {
    var url = this.getUrl('user/extension/change_on_wall', true);
    if ( !url ) {
      mpNotification.noti('user_login', '您还没有登录', '请点击浏览器右上角微信大屏幕图标登录');
      cb({'success': false, 'error_msg': '请点击浏览器右上角微信大屏幕图标以登录'});
      return;
    }
    /*if ( !this.check_account(msg) ) {
      mpNotification.noti('user_login', '账号不匹配', '您登录的公众账号与大屏幕绑定的账号不匹配，请使用绑定的公众账号登录');
      cb({'success': false, 'error_msg': '您登录的公众账号与大屏幕绑定的账号不匹配，请使用绑定的公众账号登录'});
      return;
    }*/

    $.post(url, msg, function(json){
      if ( json.info != 'ok' ) {
        if ( json.info == 'not_login' ) {
          mpNotification.noti('user_login', '您还没有登录', '请点击浏览器右上角微信大屏幕图标登录');
          json.info = '请点击浏览器右上角微信大屏幕图标以登录';
        }
        cb({'success': false, 'error_msg': json.info});
        return;
      }
      cb({'success': true, 'json':json});
    }, 'json').error(function(){
      cb({'success': false, 'error_msg':'网络连接错误，请重试'});
    });
  };

  /**
   * 检查消息状态
   */
  exports.checkOnWall = function(msg, sender, cb) {
    var url = this.getUrl('user/extension/check_on_wall', true);
    if ( !url ) {
      mpNotification.noti('user_login', '您还没有登录', '请点击浏览器右上角微信大屏幕图标登录');
      cb({'success': false, 'error_msg': '请点击浏览器右上角微信大屏幕图标以登录'});
      return;
    }
    if ( !this.check_account(msg) ) {
      //mpNotification.noti('user_login', '账号不匹配', '您登录的公众账号与大屏幕绑定的账号不匹配，请使用绑定的公众账号登录');
      cb({'success': false, 'error_msg': '您登录的公众账号与大屏幕绑定的账号不匹配，请使用绑定的公众账号登录'});
      return;
    }

    $.post(url, msg, function(json){
      if ( json.info != 'ok' ) {
        if ( json.info == 'not_login' ) {
          mpNotification.noti('user_login', '您还没有登录', '请点击浏览器右上角微信大屏幕图标登录');
          json.info = '请点击浏览器右上角微信大屏幕图标以登录';
        }
        cb({'success': false, 'error_msg': json.info});
        return;
      }
      cb({'success': true, 'result':json.result, 'is_taged':json.is_taged});
    }, 'json').error(function(){
      cb({'success': false, 'error_msg':'网络连接错误，请重试'});
    });

  };

  /**
   * 检查账号是否匹配
   */
  exports.check_account = function(msg, sender, cb)
  {
    var ret = false;
    var companyInfo = this.getCompanyInfo();

    if(companyInfo && companyInfo.id) {
      // 先匹配微信名称
      if(msg.weixin_name == companyInfo.weixin_name) {
        ret = true;
      }
      // 再匹配微信号（重新配置的情况）
      else if(companyInfo.weixin_account && msg.weixin_account == companyInfo.weixin_account) {
        ret = true;
      }
    }

    if (typeof cb == 'function') {
      cb({'success': ret, companyInfo: companyInfo});
    } else {
      return ret;
    }
  };

  /**
   * 保存配置页面的数据saveSettingData
   */
  exports.saveSettingData = function(msg, sender, cb){
    var api = this;
    var url = this.getUrl('user/extension/extension_save', true);
    if ( !url ) {
      mpNotification.noti('user_login', '您还没有登录', '请点击浏览器右上角微信大屏幕图标登录');
      cb({'success': false, 'error_msg': '请点击浏览器右上角微信大屏幕图标以登录'});
      return;
    }

    if ( !this.check_account(msg) && msg.data.is_force_config == 0 ) {
      mpNotification.noti('user_login', '账号不匹配', '您登录的公众账号与大屏幕绑定的账号不匹配，请使用绑定的公众账号登录');
      cb({'success': false, 'error_msg': '您登录的公众账号与大屏幕绑定的账号不匹配，请使用绑定的公众账号登录'});
      return;
    }

    $.post(url, msg.data, function(json){
      if ( json.info != 'ok' ) {
        if ( json.info == 'not_login' ) {
          mpNotification.noti('user_login', '您还没有登录', '请点击浏览器右上角微信大屏幕图标登录');
          json.info = '请点击浏览器右上角微信大屏幕图标以登录';
        }
        cb({'success': false, 'error_msg': json.info});
        return;
      }
      api.setUserInfo(json.user_info);
      api.setCompanyInfo(json.company_info);
      api.setCompanyInfoList(json.company_info_list);

      // 设置成功
      window._cache['is_setting_complete'] = true;

      cb({'success': true});
    }, 'json').error(function(jqXHR, textStatus, errThrown){
      cb({'success': false, 'error_msg': '网络连接错误，请重试('+textStatus+')'});
    });
  };

  /**
   * 保存上墙的消息
   */
  exports.saveMessage = function(msg, sender, cb) {
    
    var api = this;
    var url = this.getUrl('user/extension/extension_save_message', true);
    if ( !url ) {
      mpNotification.noti('user_login', '您还没有登录', '请点击浏览器右上角微信大屏幕图标登录');
      cb({'success': false, 'error_msg': '请点击浏览器右上角微信大屏幕图标以登录'});
      return;
    }
    if ( !this.check_account(msg) ) {
      mpNotification.noti('user_login', '账号不匹配', '您登录的公众账号与大屏幕绑定的账号不匹配，请使用绑定的公众账号登录');
      cb({'success': false, 'error_msg': '您登录的公众账号与大屏幕绑定的账号不匹配，请使用绑定的公众账号登录'});
      return;
    }

    // 没开通自动上墙
    var tmpWords;
    var companyInfo = this.getCompanyInfo();

    // 过滤非法关键字
    if (msg.content && msg.wall_helper == 1) {

      // 判断是否是设置了上墙时间
      if(companyInfo.auto_wall_start_time) {
        if(Date.parse(msg.mp_add_time) < Date.parse(companyInfo.auto_wall_start_time)) {
          cb({'success': false, 'error_msg': '此消息早于设置的上墙开始时间，自动屏蔽', 'error_type':'over_start_time'});
          return;
        }
      }

      // 完全匹配的不上墙
      tmpWords = window._cache['forbid_words_arr'];
      for(var i = 0; i < tmpWords.length; i++) {
        if(tmpWords[i] && tmpWords[i] === msg.content) {
          cb({'success': false, 'error_msg': '上墙的信息中包含设置的完全匹配关键字，已自动过滤', 'error_type':'forbid_words_default'});
          return;
        }
      }

      // 默认过滤的关键字
      tmpWords = window._cache['forbid_words_default_arr'];
      for(var i = 0; i < tmpWords.length; i++) {
        if(tmpWords[i] && msg.content.indexOf(tmpWords[i]) != -1) {
          cb({'success': false, 'error_msg': '上墙的信息中包含系统默认的敏感关键词', 'error_type':'forbid_words_default'});
          return;
        }
      }

      // 不完全匹配的关键字
      tmpWords = window._cache['complete_forbid_words_arr'];
      for(var i = 0; i < tmpWords.length; i++) {
        if(tmpWords[i] && msg.content.indexOf(tmpWords[i]) != -1) {
          cb({'success': false, 'error_msg': '上墙的信息中包含敏感关键词', 'error_type':'forbid_words'});
          return;
        }
      }

      // 判断是否是同一个用户的重复信息
      if(companyInfo.is_allow_user_repeat_message == 0) {
        var sentMsgArr = window._cache['sent_message_box'][msg.fakeid] || [];
        if(sentMsgArr.indexOf(msg.content) != -1) {
          cb({'success': false, 'error_msg': '用户相同的信息已经过墙', 'error_type':'repeat_message'});
          return;
        }
      }
    }
    $.post(url, msg, function(json){
      if ( json.info != 'ok' ) {
        if ( json.info == 'not_login' ) {
          mpNotification.noti('user_login', '您还没有登录', '请点击浏览器右上角微信大屏幕图标登录');
          json.info = '请点击浏览器右上角微信大屏幕图标以登录';
        }

        if(json.error_type == 'repeat_message') {
          // 将发送信息存入cache
          if(!window._cache['sent_message_box'][companyInfo.id]) {
            window._cache['sent_message_box'][companyInfo.id] = {};
          }
          if(!window._cache['sent_message_box'][companyInfo.id][msg.fakeid]) {
            window._cache['sent_message_box'][companyInfo.id][msg.fakeid] = [];
            window._cache['sent_message_box'][companyInfo.id][msg.fakeid].push(msg.content);
          }
        }

        cb({'success': false, 'error_msg': json.info, 'error_type': json.error_type ? json.error_type : ''});

        return;
      }

      // 将发送信息存入cache
      if(!window._cache['sent_message_box'][companyInfo.id]) {
        window._cache['sent_message_box'][companyInfo.id] = {};
      }
      if(!window._cache['sent_message_box'][companyInfo.id][msg.fakeid]) {
        window._cache['sent_message_box'][companyInfo.id][msg.fakeid] = [];
        window._cache['sent_message_box'][companyInfo.id][msg.fakeid].push(msg.content);
      }

      cb({'success': true, 'json': json});

    }, 'json').error(function(jqXHR, textStatus, errThrown){
      cb({'success': false, 'error_msg': '网络连接错误，请重试('+textStatus+')'});
    });
//    return true;
  };

  /**
   * 保存用户信息
   */
  exports.syncUser = function(data, sender, cb){
    var url = this.getUrl('user/extension/extension_user_save', true);
    if ( !url ) {
      cb({'success': false, 'error_msg': '请点击浏览器右上角微信大屏幕图标以登录'});
      return;
    }
    if ( !this.check_account(data) ) {
      cb({'success': false, 'error_msg': '您登录的公众账号与大屏幕绑定的账号不匹配，请使用绑定的公众账号登录'});
      return;
    }
    $.post(url, data, function(json){
      if ( json.info != 'ok' ) {
        if ( json.info == 'not_login' ) {
          json.info = '请点击浏览器右上角微信大屏幕图标以登录';
        }
        cb({'success': false, 'error_msg': json.info});
        return;
      }
      cb({'success': true, 'fakeid':json.fakeid});
    }, 'json').error(function(){
      cb({'success': false, 'fakeid':null});
    });
  };

  /**
   * 获取并组装url, 查看大屏幕的链接，
   */
  exports.getCompanyUrl = function(path, needCompanyId)
  {
    var url = this.getUrl(path, needCompanyId);
    url = url.replace(window._cache['siteUrl'], window._cache['companyUrl']);
    return url;
  }
  
  /**
   * 获取并组装url
   */
  exports.getUrl = function(path, needCompanyId)
  {
    var siteUrl   = window._cache['siteUrl'];
    var url = '';
    if ( needCompanyId ) {
      var companyInfo = this.getCompanyInfo();
      var companyId = companyInfo ? companyInfo.id : 0;
      if ( !companyId ) {
        return '';
      }
      url = siteUrl + '/' + companyId + '/' + path;
    } else {
      url = siteUrl + '/' + path;
    }

    if (url.indexOf('?') != -1) {
      url = url + '&is_extension=1';
    } else {
      url = url + '?is_extension=1';
    }
    return url;
  };

  /**
   * 监测服务器节点状态
   */
  exports.pullServerState = function()
  {
    var url = window._cache['server_proxyUrl'];
    $.getJSON(url, function(json){
      if(json.info != 'ok') {
        console.log('api.getServerState failed: json.info:' , json.info);
        return false;
      }
      if(!json.node_list) {
        console.log('api.getServerState failed: node_list is empty', json);
        return false;
      }
      var aliveUrl = '';
      for(var sUrl in json.node_list) {
        if(json.node_list[sUrl] == 'alive') {
           aliveUrl = sUrl;
          break;
        }
      }
      if(!aliveUrl) {
        console.log('api.getServerState failed: aliveUrl is empty', json);
        return false;
      }

      if(aliveUrl != window._cache['siteUrl']) {
        // 更改siteUrl
        window._cache['last_siteUrl']       = window._cache['siteUrl'];
        window._cache['siteUrl']            = aliveUrl;
        window._cache['server_proxyResult'] = json;

        // 更改大屏幕的地址
        chrome.tabs.query({
          url: "http://*.wxscreen.com/*",
          windowType: "normal"
        }, function(tabs){
          if ( tabs.length ) {
            for( var i =0; i<tabs.length; i++) {
              var newUrl = tabs[i].url.replace(window._cache['last_siteUrl'], window._cache['siteUrl']);
              // 重新加载
              chrome.tabs.update(tabs[i].id, {
                url: newUrl
              });
            }
          }
        });
      }

    }).error(function(){
      console.log("api.getServerState failed", arguments);
    });
  };

  /**
   * 获取token
   */
  exports.getToken = function(cb){
    chrome.tabs.query({
      url: "https://mp.weixin.qq.com/cgi-bin/*",
      windowType: "normal"
    }, function(tabs){
      if ( tabs.length ) {
        for( var i =0; i<tabs.length; i++) {
          var urlArr = common.parseUrl(tabs[i].url);
          if ( urlArr.queryParams.token ) {
            cb(urlArr.queryParams.token);
            return;
          }
        }
      }
      cb('');
    });
  };

  /**
   * 获取日期格式
   */
  exports.getDate = function(timestampMs)
  {
    var tmpD = new Date;
    if(timestampMs) tmpD.setTime(timestampMs);
    var year, month, day, hour, minute, second;

    year = tmpD.getFullYear();

    month = (tmpD.getMonth() + 1) + '';
    if (month.length < 2) month = '0' + month;

    date = tmpD.getDate() + '';
    if (date.length < 2) date = '0' + date;

    hour = tmpD.getHours() + '';
    if(hour.length < 2) hour = '0' + hour;

    minute = tmpD.getMinutes() + '';
    if (minute.length < 2) minute = '0' + minute;

    second = tmpD.getSeconds() + '';
    if (second.length < 2) second = '0' + second;

    return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
  };

  /**
   * 错误提示接口
   */
  exports.error = function(msg, sender, cb){

  };
});